package com.jash.networkpack;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.Map;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class MainActivity extends AppCompatActivity implements Callback<Entity> {
    private ArrayAdapter<String> adapter;

//    private TextView text;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
//        text = (TextView) findViewById(R.id.main_text);
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://m2.qiushibaike.com/")
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .build();
        HttpService service = retrofit.create(HttpService.class);
        service.getText(1).enqueue(this);
        ListView listView = (ListView) findViewById(R.id.main_list);
        adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, new ArrayList<>());
        listView.setAdapter(adapter);
        service.getRxJava(1)
                .subscribeOn(Schedulers.io())
                .observeOn(Schedulers.io())
                .flatMap(entity -> Observable.from(entity.getItems()))
                .map(ItemEntity::getContent)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(adapter::add, Throwable::printStackTrace);
    }

    @Override
    public void onResponse(Call<Entity> call, Response<Entity> response) {
        Entity body = response.body();
//        text.setText(body.getItems().get(0).getContent());
    }

    @Override
    public void onFailure(Call<Entity> call, Throwable t) {
        t.printStackTrace();
        Toast.makeText(this, t.getMessage(), Toast.LENGTH_SHORT).show();
    }
}
